#!/bin/bash

# AI-CRM 数据备份脚本

BACKUP_DIR="./backups"
TIMESTAMP=$(date +%Y%m%d_%H%M%S)

echo "================================"
echo "  AI-CRM 数据备份脚本"
echo "================================"
echo ""

# 创建备份目录
mkdir -p $BACKUP_DIR

echo "开始备份数据库..."

# 备份共享 MySQL（包含 Cordys 和 DataEase 数据库）
echo "备份共享 MySQL（Cordys + DataEase）..."
docker exec shared-mysql mysqldump -uroot -pshared_mysql_root_password --databases cordys dataease > "$BACKUP_DIR/shared_mysql_$TIMESTAMP.sql"

# 备份 SQLBot PostgreSQL
echo "备份 SQLBot PostgreSQL..."
docker exec sqlbot-postgres pg_dump -U sqlbot sqlbot > "$BACKUP_DIR/sqlbot_postgres_$TIMESTAMP.sql"

# 压缩备份文件
echo "压缩备份文件..."
tar -czf "$BACKUP_DIR/ai-crm-backup_$TIMESTAMP.tar.gz" \
    "$BACKUP_DIR/shared_mysql_$TIMESTAMP.sql" \
    "$BACKUP_DIR/sqlbot_postgres_$TIMESTAMP.sql"

# 删除临时 SQL 文件
rm "$BACKUP_DIR/shared_mysql_$TIMESTAMP.sql"
rm "$BACKUP_DIR/sqlbot_postgres_$TIMESTAMP.sql"

echo ""
echo "备份完成！"
echo "备份文件: $BACKUP_DIR/ai-crm-backup_$TIMESTAMP.tar.gz"
echo ""

# 清理旧备份（保留最近 7 天）
echo "清理 7 天前的备份文件..."
find $BACKUP_DIR -name "ai-crm-backup_*.tar.gz" -mtime +7 -delete

echo "备份任务完成"

